package com.leyou.search.service.impl;

import com.leyou.common.dto.PageDTO;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.SkuDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.dto.SpuDTO;
import com.leyou.search.pojo.Goods;
import com.leyou.search.repository.GoodsRepository;
import com.leyou.search.service.IndexService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class IndexServiceImpl implements IndexService {

    @Autowired
    private ItemClient itemClient;

    @Autowired
    private GoodsRepository repository;


    /**
     * goods对象的生成
     *
     * @param spuDTO
     * @return
     */
    @Override
    public Goods buildGoods(SpuDTO spuDTO) {
        Goods goods = new Goods();

        BeanUtils.copyProperties(spuDTO, goods);


        //categoryId
        goods.setCategoryId(spuDTO.getCid3());

        //suggestion

        List<String> suggest = new ArrayList<>();

        String bName = spuDTO.getBrandName();
        suggest.add(bName);

        //categoryName,手机/手机通讯/手机

        String cName = spuDTO.getCategoryName().split("/")[2];
        suggest.add(cName);


        suggest.add(spuDTO.getName());


//        int subLength = bName.indexOf("（") == -1 ? bName.length() : bName.indexOf("（");
//
//        String shortBName = bName.substring(0, subLength);

        String shortBName = StringUtils.substringBefore(bName,"（");

        suggest.add(shortBName + cName);
        suggest.add(cName + shortBName);
        goods.setSuggestion(suggest);

        //根据spuId查询对应的sku信息

        List<SkuDTO> skuDTOS = this.itemClient.querySkuBySpuId(spuDTO.getId());

        //image

        goods.setImage(StringUtils.substringBefore(skuDTOS.get(0).getImages(),","));


        //prices

        Set<Long> prices = new HashSet<>();

        Long sold = 0L;


        for (SkuDTO skuDTO : skuDTOS) {
            sold+=skuDTO.getSold();
            prices.add(skuDTO.getPrice());
        }


        goods.setPrices(prices);

        //sold
        goods.setSold(sold);


        //specs

        List<Map<String, Object>> specs = new ArrayList<>();

        //查询当前商品对应的所有的可搜索规格参数以及其对应的值
        List<SpecParamDTO> specParamDTOS = this.itemClient.querySpecsValues(spuDTO.getId(), true);


        specParamDTOS.forEach(specParamDTO -> {
            Map<String,Object> resultMap = new HashMap<>();

            resultMap.put("name",specParamDTO.getName());
            resultMap.put("value",chooseSegment(specParamDTO));

            specs.add(resultMap);
        });


        goods.setSpecs(specs);


        //updateTime


        return goods;
    }


    private Object chooseSegment(SpecParamDTO p) {
        Object value = p.getValue();
        if (value == null || StringUtils.isBlank(value.toString())) {
            return "其它";
        }
        if (!p.getNumeric() || StringUtils.isBlank(p.getSegments()) || value instanceof Collection) {
            return value;
        }
        double val = parseDouble(value.toString());
        String result = "其它";
        // 保存数值段
        for (String segment : p.getSegments().split(",")) {
            String[] segs = segment.split("-");
            // 获取数值范围
            double begin = parseDouble(segs[0]);
            double end = Double.MAX_VALUE;
            if (segs.length == 2) {
                end = parseDouble(segs[1]);
            }
            // 判断是否在范围内
            if (val >= begin && val < end) {
                if (segs.length == 1) {
                    result = segs[0] + p.getUnit() + "以上";
                } else if (begin == 0) {
                    result = segs[1] + p.getUnit() + "以下";
                } else {
                    result = segment + p.getUnit();
                }
                break;
            }
        }
        return result;
    }

    private double parseDouble(String str) {
        try {
            return Double.parseDouble(str);
        } catch (Exception e) {
            return 0;
        }
    }


    @Override
    public void loadData() {
        try {
            repository.deleteIndex();
        } catch (Exception e) {
        }

        Boolean index = repository.createIndex("{\n" +
                "  \"settings\": {\n" +
                "    \"analysis\": {\n" +
                "      \"analyzer\": {\n" +
                "        \"my_pinyin\": {\n" +
                "          \"tokenizer\": \"ik_smart\",\n" +
                "          \"filter\": [\n" +
                "            \"py\"\n" +
                "          ]\n" +
                "        }\n" +
                "      },\n" +
                "      \"filter\": {\n" +
                "        \"py\": {\n" +
                "\t\t  \"type\": \"pinyin\",\n" +
                "          \"keep_full_pinyin\": true,\n" +
                "          \"keep_joined_full_pinyin\": true,\n" +
                "          \"keep_original\": true,\n" +
                "          \"limit_first_letter_length\": 16,\n" +
                "          \"remove_duplicated_term\": true\n" +
                "        }\n" +
                "      }\n" +
                "    }\n" +
                "  },\n" +
                "  \"mappings\": {\n" +
                "    \"properties\": {\n" +
                "      \"id\": {\n" +
                "        \"type\": \"keyword\"\n" +
                "      },\n" +
                "      \"suggestion\": {\n" +
                "        \"type\": \"completion\",\n" +
                "        \"analyzer\": \"my_pinyin\",\n" +
                "        \"search_analyzer\": \"ik_smart\"\n" +
                "      },\n" +
                "      \"title\":{\n" +
                "        \"type\": \"text\",\n" +
                "        \"analyzer\": \"my_pinyin\",\n" +
                "        \"search_analyzer\": \"ik_smart\"\n" +
                "      },\n" +
                "      \"image\":{\n" +
                "        \"type\": \"keyword\",\n" +
                "        \"index\": false\n" +
                "      },\n" +
                "      \"updateTime\":{\n" +
                "        \"type\": \"date\"\n" +
                "      },\n" +
                "      \"specs\":{\n" +
                "        \"type\": \"nested\",\n" +
                "        \"properties\": {\n" +
                "          \"name\":{\"type\": \"keyword\" },\n" +
                "          \"value\":{\"type\": \"keyword\" }\n" +
                "        }\n" +
                "      }\n" +
                "    }\n" +
                "  }\n" +
                "}");
        System.out.println("index = " + index);


        //获取到spu，转换为goods，最终保存

        int page = 1;
        while (true) {
            PageDTO<SpuDTO> spuDTOPageDTO = this.itemClient.pageQuery(page, 50, null, null, null, null);
            System.out.println("spuDTOPageDTO = " + spuDTOPageDTO);
            //没有数据结束
            if (spuDTOPageDTO.getTotalPage() == 0) {
                break;
            }


            List<Goods> goodsList = spuDTOPageDTO.getItems().stream().map(this::buildGoods).collect(Collectors.toList());

            repository.saveAll(goodsList);


            page++;

            //下一页不存在则停止
            if (page > spuDTOPageDTO.getTotalPage()) {
                break;
            }

        }
    }

    @Override
    public void saveGoodsById(Long spuId) {

        //supDTO==>goods


        //根据spuId 查询对应的spu 对象
        List<SpuDTO> items = this.itemClient.pageQuery(null, null, null, null, null, spuId).getItems();

        //当值存在时,吧spuDTO转化为goods 然后保存
        if (!CollectionUtils.isEmpty(items)) {

            this.repository.save(buildGoods(items.get(0)));
        }
    }

    @Override
    public void deleteGoodsById(Long spuId) {
        this.repository.deleteById(spuId);
    }
}